package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppRoomDao;
import com.vf.admin.client.dto.AppRoomDto;
import com.vf.admin.client.dto.UserDto;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.vf.admin.client.common.ClientConstants.cz_no;
import static com.vf.admin.client.common.ClientConstants.cz_yes;
import static com.vf.admin.common.Constants.*;
import static com.vf.admin.utils.DatesUtil.isDay;
import static com.vf.admin.utils.StringEx.isNull;

/**
 * 首页
 *
 * @author anxiang
 */
@Controller
@RequestMapping("/app/home")
public class AppHomeController extends ClientBaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    AppRoomService appRoomService;
    @Autowired
    AppRoomDao appRoomDao;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppMingxiJinbiService appMingxiJinbiService;
    @Autowired
    AppDashanService appDashanService;
    @Autowired
    AppRoomCollectService appRoomCollectService;
    @Autowired
    AppPrivilegeService appPrivilegeService;
    @Autowired
    AppFansClubService appFansClubService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 获取首页视频直播
     *
     * @return
     */
    @RequestMapping("/splist")
    @ResponseBody
    public Result splist() {

        List<AppRoom> splist = appRoomDao.splist();
        Map<String, Object> mm = new HashMap<>(16);
        mm.put("list", splist);
        return sucessJSON(mm);
    }

    /**
     * 获取首页情感专家
     *
     * @return
     */
    @RequestMapping("/getEmotionExpert")
    @ResponseBody
    public Result getEmotionExpert() {
        AppSetup setup = appSetupService.get();
        AppRoom room = appRoomService.getRoomCode(setup.getQingganroom() + "");
        Map<String, Object> mm = new HashMap<>(16);
        //房间id
        mm.put("id", room != null ? room.getId() : null);
        //房间code
        mm.put("roomcode", room != null ? room.getRoomcode() : null);
        //房间性质  1、音频 2、视频
        mm.put("roomtype", room != null ? room.getXingzhi() : null);
        //房间的腾讯code
        mm.put("txcode", room != null ? room.getTengxuncode() : null);
        if(room != null) {
            mm.put("roompass", isNull(room.getRoompass()) ? "" : room.getRoompass());
        } else {
            mm.put("roompass", "");
        }
        //是否开启房间密码  1开启  2未开启 默认：1正常
        mm.put("passstate", room != null ? room.getPassstate() : null);
        mm.put("kbzhuangtai", room != null ? room.getKbzhuangtai() : null);
        return sucessJSON(mm);
    }

    /**
     * 根据房间分类分页获取房间
     *
     * @param pageno 第几页
     * @param type   1语聊房  2视频房
     * @return
     */
    @RequestMapping("/getRoomByCat")
    @ResponseBody
    public Result getRoomByCat(Integer pageno,
                               @RequestParam(value = "value", required = false) Integer type) {
        if (StringUtils.isEmpty(pageno)) {
            return errorJSON("pageno不能为空");
        }
        SplitPageBean splitPageBean = new SplitPageBean(pageno, 20);
        List<AppRoom> roomList = appRoomService.getTypeRoomList(type, splitPageBean);
        List<AppRoomDto> toList = new ArrayList<>();
        //先查询redis  获取房间在线人数
        Map<Object, Object> map = redisUtil.hmget("RoomOnline");
        Map<Integer, Integer> onMap = new HashMap<>(16);
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            onMap.put(Integer.valueOf(mapKey.toString()), Integer.valueOf(mapValue.toString()));
        }
        for (AppRoom room : roomList) {
            //数据迁移至dto
            AppRoomDto ard = new AppRoomDto();
            BeanUtils.copyProperties(room, ard);
            ard.setRoompass(isNull(room.getRoompass()) ? "" : room.getRoompass());
            //在线人数初值为0
            int zaixian = 0;
            //判断map中是否存在该房间的在线人数
            if (onMap.containsKey(room.getTengxuncode())) {
                //存在   则赋值
                zaixian = Integer.valueOf(onMap.get(room.getTengxuncode()).toString());
            }
            //放入在线人数
            ard.setOnlinenum(zaixian);
            toList.add(ard);
        }
        return sucessPage(toList, splitPageBean.getNextPageNo());
    }

    /**
     * 获取房间分类
     *
     * @return
     */
    @RequestMapping("/getRoomAllCat")
    @ResponseBody
    public Result getRoomAllCat() {
        List<AppRoomType> roomAllCat = appRoomService.getRoomAllCat(2);
        Map<String, Object> resultMap = new HashMap<>(16);
        resultMap.put("list", roomAllCat);
        return sucessJSON(resultMap);
    }


    /**
     * 获取收藏的房间
     *
     * @param pageno 页码
     * @return
     */
    @RequestMapping("/getRoomCollection")
    @ResponseBody
    public Result getRoomCollection(Integer pageno) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        SplitPageBean splitPage = new SplitPageBean(pageno, 20);
        List<AppRoomCollect> list = appRoomCollectService.findList(appUser.getId(), splitPage);

        String roomArr = "";
        for (AppRoomCollect roomCollect : list) {
            roomArr += "," + roomCollect.getRoomid();
        }
        if (!isNull(roomArr)) {
            roomArr = roomArr.substring(1);
        }
        Map<Integer, Integer> roomMap = new HashMap<>(16);
        if (!isNull(roomArr)) {
            List<AppRoom> roomList = appRoomService.getPiliang(roomArr);
            for (AppRoom room : roomList) {
                roomMap.put(room.getId(), room.getKbzhuangtai());
            }
        }


        //先查询redis  获取房间在线人数
        Map<Object, Object> map = redisUtil.hmget("RoomOnline");
        Map<Integer, Integer> onMap = new HashMap<>(16);
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            onMap.put(Integer.valueOf(mapKey.toString()), Integer.valueOf(mapValue.toString()));
        }
        for (AppRoomCollect roomCollect : list) {
            //在线人数初值为0
            int zaixian = 0;
            //判断map中是否存在该房间的在线人数
            if (onMap.containsKey(roomCollect.getTengxuncode())) {
                //存在   则赋值
                zaixian = Integer.valueOf(onMap.get(roomCollect.getTengxuncode()).toString());
            }
            //获取房间直播状态
            if (roomMap.containsKey(roomCollect.getRoomid())) {
                //存在则放入
                roomCollect.setKbzhuangtai(roomMap.get(roomCollect.getRoomid()));
            } else {
                //不存在
                roomCollect.setKbzhuangtai(2);
            }
            //放入在线人数
            roomCollect.setOnlinenum(zaixian);
        }
        return sucessPage(list, splitPage.getNextPageNo());
    }

    /**
     * @Description 是否可以发送文字消息
     * @return: com.vf.admin.common.entity.Result
     * @Author: xzx
     * @Date: 2021/10/30
     */
    @ResponseBody
    @RequestMapping("/isSendTextMessage")
    public Result isSendTextMessage() {
        try {
            System.out.println("token:" + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            Map<String, Object> map = new HashMap<>(16);
            map.put("message", "实名认证后,可无限制发送文字消息");
            if (user.getStatus().equals(STATUS_QY) || user.getSex().equals(SEX_STATE_NV)) {
                map.put("isjixu", cz_yes);
                //等于无限制
                map.put("shengyu", 100000);
            } else {
                AppSetup setup=appSetupService.get();
                //未实名
                //判断上一次记录时间是否是今天
                if (!isNull(user.getMessagetime())) {

                    if (isDay(user.getMessagetime())) {
                        //是今天  判断数量是否大于10
                        if (user.getMessagenum() >= setup.getDaysmsnum()) {
                            map.put("isjixu", cz_no);
                            //剩余数量为0
                            map.put("shengyu", 0);
                        } else {
                            map.put("isjixu", cz_yes);
                            int num = setup.getDaysmsnum() - (user.getMessagenum());
                            map.put("shengyu", num);
                        }
                    } else {
                        map.put("isjixu", cz_yes);
                        map.put("shengyu", setup.getDaysmsnum());
                    }
                } else {
                    map.put("isjixu", cz_yes);
                    map.put("shengyu", setup.getDaysmsnum());
                }
            }
            return sucessJSON(map, "查询成功");
        } catch (Exception e) {
            logger.error("音视频聊天余额是否充足异常", e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        }
    }


    /**
     * @Description 变更发送文字消息次数
     * @return: com.vf.admin.common.entity.Result
     * @Author: xzx
     * @Date: 2021/10/30
     */
    @ResponseBody
    @RequestMapping("/updateSendTextMessage")
    public Result updateSendTextMessage() {
        try {
            //获取当前登录用户的user对象
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            AppSetup setup = appSetupService.get();
            Map<String, Object> map = new HashMap<>(16);
            map.put("message", "实名认证后,可无限制发送文字消息");
            if (user.getStatus().equals(STATUS_QY) || user.getSex().equals(SEX_STATE_NV)) {
                map.put("shengyu", 100000);
            } else {
                //未实名
                //判断上一次记录时间是否是今天
                if (!isNull(user.getMessagetime())) {
                    if (isDay(user.getMessagetime())) {
                        //是今天  判断数量是否大于10
                        if (user.getMessagenum() < setup.getDaysmsnum()) {
                            //修改文字消息发送数量
                            appUserService.addMessage(user.getId(), cz_no);
                            map.put("shengyu", setup.getDaysmsnum() - user.getMessagenum() - 1);
                        } else {
                            map.put("shengyu", 0);
                        }
                    } else {
                        //修改文字消息发送数量
                        appUserService.addMessage(user.getId(), cz_yes);
                        map.put("shengyu", setup.getDaysmsnum() - 1);
                    }
                } else {
                    //修改文字消息发送数量
                    appUserService.addMessage(user.getId(), cz_yes);
                    map.put("shengyu", setup.getDaysmsnum() - 1);
                }
            }
            return sucessJSON(map, "成功");
        } catch (Exception e) {
            this.logger.debug("变更发送文字消息次数异常" + e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        }
    }


    /**
     * 房间搜索
     *
     * @return
     */
    @RequestMapping("/searchRoom")
    @ResponseBody
    public Result searchRoom(String sousuo, Integer pageno) {
        try {
            System.out.println("页码:" + pageno);
            if (isNull(sousuo)) {
                return errorJSON("搜索条件不能为空");
            }
            if (pageno == null || pageno <= 0) {
                return this.errorJSON("没有更多数据了！");
            }
            SplitPageBean splitPage = new SplitPageBean(pageno, 20);
            List<AppRoom> roomList = appRoomService.getSearch(sousuo, splitPage);
            List<AppRoomDto> toList = new ArrayList<>();
            //先查询redis  获取房间在线人数
            Map<Object, Object> map = redisUtil.hmget("RoomOnline");
            Map<Integer, Integer> onMap = new HashMap<>(16);
            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                Object mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                onMap.put(Integer.valueOf(mapKey.toString()), Integer.valueOf(mapValue.toString()));
            }
            for (AppRoom room : roomList) {
                //数据迁移至dto
                AppRoomDto ard = new AppRoomDto();
                BeanUtils.copyProperties(room, ard);
                //在线人数初值为0
                int zaixian = 0;
                //判断map中是否存在该房间的在线人数
                if (onMap.containsKey(room.getTengxuncode())) {
                    //存在   则赋值
                    zaixian = Integer.valueOf(onMap.get(room.getTengxuncode()).toString());
                }
                //放入在线人数
                ard.setOnlinenum(zaixian);
                toList.add(ard);
            }
            return sucessPage(roomList, splitPage.getNextPageNo());
        } catch (Exception e) {
            logger.error("房间搜索异常", e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        }
    }


    /**
     * 用户搜索
     *
     * @return
     */
    @RequestMapping("/searchUser")
    @ResponseBody
    public Result searchUser(String sousuo, Integer pageno) {
        try {
            System.out.println("页码:" + pageno);

            if (isNull(sousuo)) {
                return errorJSON("搜索条件不能为空");
            }
            if (pageno == null || pageno <= 0) {
                return this.errorJSON("没有更多数据了！");
            }
            SplitPageBean splitPage = new SplitPageBean(pageno, 20);
            List<AppUser> userList = appUserService.getSearch(sousuo, splitPage);
            List<UserDto> toList = new ArrayList<>();
            for (AppUser user : userList) {
                //数据迁移至dto
                UserDto ud = new UserDto();
                BeanUtils.copyProperties(user, ud);
                //判断用户是否是贵族
                if (user.getIsguizu() == 1) {
                    //是贵族
                    //根据贵族id  获取贵族图标
                    String medal = guizuCacheMap.get(user.getNobleid());
                    ud.setMedal(medal);
                } else {
                    ud.setMedal("");
                }
                toList.add(ud);
            }
            return sucessPage(toList, splitPage.getNextPageNo());
        } catch (Exception e) {
            logger.error("房间搜索异常", e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        }
    }
}
